from flask import Flask, request, render_template, send_from_directory, redirect, url_for, send_file
import os
import pdfplumber
from docx import Document
import zipfile
import io

UPLOAD_FOLDER = 'Tools/uploads'
MD_FOLDER = 'Tools/md'
DOCX_FOLDER = 'Tools/docx'

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MD_FOLDER'] = MD_FOLDER
app.config['DOCX_FOLDER'] = DOCX_FOLDER

os.makedirs(UPLOAD_FOLDER, exist_ok=True)
os.makedirs(MD_FOLDER, exist_ok=True)
os.makedirs(DOCX_FOLDER, exist_ok=True)

def pdf_to_md(pdf_path, md_path):
    with pdfplumber.open(pdf_path) as pdf:
        text = ''
        for page in pdf.pages:
            text += page.extract_text() or ''
            text += '\n\n'
    with open(md_path, 'w', encoding='utf-8') as f:
        f.write(text)

def pdf_to_docx(pdf_path, docx_path):
    doc = Document()
    with pdfplumber.open(pdf_path) as pdf:
        for page in pdf.pages:
            text = page.extract_text() or ''
            doc.add_paragraph(text)
    doc.save(docx_path)

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        files = request.files.getlist('pdfs')
        for file in files:
            filename = file.filename
            save_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
            file.save(save_path)
            md_path = os.path.join(app.config['MD_FOLDER'], filename + '.md')
            docx_path = os.path.join(app.config['DOCX_FOLDER'], filename + '.docx')
            pdf_to_md(save_path, md_path)
            pdf_to_docx(save_path, docx_path)
        return redirect(url_for('index'))
    md_files = os.listdir(app.config['MD_FOLDER'])
    docx_files = os.listdir(app.config['DOCX_FOLDER'])
    return render_template('index.html', md_files=md_files, docx_files=docx_files)

@app.route('/download/md/<filename>')
def download_md(filename):
    return send_from_directory(app.config['MD_FOLDER'], filename, as_attachment=True)

@app.route('/download/docx/<filename>')
def download_docx(filename):
    return send_from_directory(app.config['DOCX_FOLDER'], filename, as_attachment=True)

@app.route('/download/all')
def download_all():
    md_files = [os.path.join(app.config['MD_FOLDER'], f) for f in os.listdir(app.config['MD_FOLDER'])]
    docx_files = [os.path.join(app.config['DOCX_FOLDER'], f) for f in os.listdir(app.config['DOCX_FOLDER'])]
    mem_zip = io.BytesIO()
    with zipfile.ZipFile(mem_zip, 'w') as zf:
        for f in md_files:
            zf.write(f, os.path.join('md', os.path.basename(f)))
        for f in docx_files:
            zf.write(f, os.path.join('docx', os.path.basename(f)))
    mem_zip.seek(0)
    return send_file(mem_zip, mimetype='application/zip', as_attachment=True, download_name='converted_files.zip')

if __name__ == '__main__':
    app.run(debug=True)
